<?php
namespace Home\Controller;

use Think\Controller;
use WechatSdk\Wechat;
use Home\Controller\MobileBaseController;

class PayController extends MobileBaseController{
        
    public function index() {     
		//需要获取用户信息
		$mpid       = get_mpid();
		$openid     = get_openid(); 

		//根据id获取商品信息
        $goods  = M('goods');
        $id     = $_GET['id'];
        $pay    = $goods->where(array('id'=>$id))->find();
		if($pay['status'] != '上架'){
			$this->ajaxReturn('商品未上架');
			//$this->error('商品未上架','index.php');
		}
		
		$member = M('member');
		$m_info = $member->where(array('openid'=>$openid))->find();
		
		//测试输出 -zsyk
		//print_r($fans_info);
		//print_r($_SESSION);		
		
        $this->assign('pay',$pay);
        $this->assign('member',$m_info);
        $this->display();
    }

	public function add() {
		//$openid = 'textopenid'; // 测试数据，模拟微信用户OpenID，用于模拟判断是否是第一次购买 -zsyk
		$openid    = get_openid(); 		
        if (IS_POST) {
            //自动验证用户表(member)的字段值
            $_validate = array(
                array('telephone', 'require', '手机号不能为空', 1, 'regex', 3),
                array('telephone', '11', '请输入正确的手机号', 2, 'length', 1),
                array('nickname', 'require', '未能正确获取昵称', 1, 'regex', 1),
            );
            //连接数据库
            $member = M('member');
            $order  = M('order');
            $goods  = M('goods');
            $user_good_order = M('user_good_order');
            //验证member表
            //$member->setProperty('_validate', $_validate);
            
            $mobile = $_POST['mobile'];
            $code   = $_POST['code'];
            $mobile_notice = $_POST['mobile_notice'];			
            //判断用户是否是会员
            $ishave = $member->where('telephone= "'.$mobile.'"')->count();
            if($ishave > 0){													//会员非首次购买
                $this->ajaxReturn('首次免费机会已使用');
                $this->redirect('Home/index', array('mpid' => 1), 2, '页面跳转中...');
            }else{
                //会员首次购买插用户信息表
                if($_SESSION['code'] == $code ){					
                    $data['openid']     = $openid;				
                    $data['city']       = get_fans_info($openid, 'city');
                    $data['nickname']   = get_fans_nickname($openid);
                    $data['telephone']  = $mobile;
                    $data['createtime'] = date('Y-m-d H:i:s',time());
                    $data['flag']       = '1';					
                    $results_member     = $member->data($data)->add(); 			//创建会员信息,返回记录id -zsyk
                    if($results_member){
						$mess = '用户信息录入成功.';
						// 首次用户订单插订单表
						$order_data['goods_id']    = $_POST['goods_id'];
						$order_data['goods_name']  = $_POST['goods_name'];
						$order_data['goods_price'] = $_POST['goods_price'];
						$order_data['member_id']   = $results_member;
						$order_data['buytime']     = time();
						$order_data['status']      = '1';
						//支付状态码：0：首次体验不需支付，1：支付成功，其他则使用微信支付接口的返回代码
						$order_data['pay_status']  = '0';						
						//16位订单号
						$order_data['number']      = substr(time().mt_rand(), 0,16);
						$results_order             = $order->data($order_data)->add();  //创建订单 -zsyk
						if($results_order){
							$mess .= '订单提交成功.';
						}else{
							$mess .= '订单提交失败.';
						}						
                    }else{
                        $mess = '用户信息录入失败.';
                    }
					$this->ajaxReturn($mess);
                }else{
                    $this->ajaxReturn('验证码错误');
                }
            }
        }else{
			$this->redirect('Home/index', array('mpid' => 1), 2, '数据提交不合法，页面跳转中...');
			exit('error');
		}
    }
/*
*用户再次购买，需要支付
*/
	public function buy() {
		//init_fans(); //初始化粉丝信息
		$openid    = get_openid(); 
		
        if (IS_POST) {
            //连接数据库
            $member  = M('member');
            $mp_fans = M('mp_fans');
            $order   = M('order');
            $goods   = M('goods');
            $user_good_order = M('user_good_order');
            //验证member表
            //$member->setProperty('_validate', $_validate);
            
            //判断用户是否是会员并且关注公众号
			$q_data = array('is_subscribe' => 1, 'openid' => $openid);
            //$ishave = $member->where('telephone= "'.$mobile.'"')->count();
			$ishave = $member->where('openid= "'.$openid.'"')->find();
			$is_subscribe = $mp_fans->where($q_data)->count();
            if($ishave['id'] > 0 && $is_subscribe > 0){  //会员非首次购买
				$order_data['goods_id']    = $_POST['goods_id'];
				$order_data['goods_name']  = $_POST['goods_name'];
				$order_data['goods_price'] = $_POST['goods_price'];
				$order_data['member_id']   = $ishave['id'];
				$order_data['buytime']     = time();
				$order_data['status']      = 0;
				$order_data['pay_status']  = 0;	
				//16位订单号
				$order_data['number']= substr(time().mt_rand(), 0,16);
				$results_order       = $order->data($order_data)->add();				
				$re_data['orderid']  = $results_order;
				$re_data['mpid']     = get_mpid();
				$re_data['openid']   = $openid;
				$re_data['money']    = $order_data['goods_price'];
				$re_data['number']   = $order_data['number'];
				$re_data['buytime']  = $order_data['buytime'];
				if (!$results_order) {
					$re_data['errcode'] = 0;
					$re_data['errmsg']  = '购买失败';
				} else {
					$re_data['errcode']  = 1;
					$re_data['errmsg']   = '订单已生成';
					$re_data['notify']   = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?s=Home/Pay/pay_ok';
					$re_data['jump_url'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?s=Home/Pay/pay_ok';
				}
				$this->ajaxReturn($re_data);
            }else{
				$this->redirect('Home/index', array('mpid' => 1), 2, '数据提交不合法，页面跳转中...');
            }
        }else{
			$this->redirect('Home/index', array('mpid' => 1), 2, '数据提交不合法，页面跳转中...');
			exit('error');
		}
    }

	
	
	//支付成功
	public function pay_ok() {
		$pay_info = I('get.');
		if (I('result_code') == 'SUCCESS' && I('return_code') == 'SUCCESS') {
			$map['id']     = I('out_trade_no');
			$data['pay_status'] = 1;
			$data['status']     = 1;
			M('order')->where($map)->save($data);
		}
		print_r($map);
        $this->assign('pay',$pay_info);
		$this->display();
	}

    /**
     * 订单列表
     * 
     */
    public function lists() {
        $this->addCrumb('系统管理', U('Index/index'), '')
             ->addCrumb('订单管理', U('Goods/lists'), '')
             ->addCrumb('订单列表', '', 'active')
             ->addNav('订单列表', '', 'active')
             ->setModel('order')
             ->setListOrder('id desc')
             ->setListSearch(array(
                'number' => '订单号',
                'buytime' => '下单时间'
             ))
             ->addListItem('number', '订单号')
             ->addListItem('good_id', '商品名称', 'callback', array('callback_name'=>'order_goods'))
             ->addListItem('user_id', '用户名称', 'callback', array('callback_name'=>'order_user'))
             ->addListItem('buytime', '下单时间')
             ->addListItem('status', '状态')
             // ->addListItem('status', '用户角色', 'callback', array('callback_name'=>'parse_roles'))
             // ->addListItem('register_time', '注册时间', 'function', array('function_name'=>'date','params'=>'Y-m-d H:i:s,###'))
             ->addListItem('id', '操作', 'custom', array('options'=>array('edit'=>array('编辑',U('edit',array('id'=>'{id}')),'btn btn-primary btn-sm icon-edit',''),'delete'=>array('删除',U('delete',array('id'=>'{id}')),'btn btn-danger btn-sm icon-delete', ''))))
             ->setListPer(5)
             ->common_lists();
    }

    public function get_goods_name() {
        $results = M('goods')->select();
        foreach ($results as $k => $v) {
            $goods[$v['id']] = $v['name'];
        }
        return $goods;
    }

    public function get_user_name() {
        $results = M('user')->select();
        foreach ($results as $k => $v) {
            $users[$v['id']] = $v['username'];
        }
        return $users;
    }


    /**
     * 格式化显示用户所属角色
     * @author 艾逗笔<765532665@qq.com>
     */
    public function order_goods($good_id) {
        $order_goods = M('user_good_order')->field('good_id')->where(array('good_id'=>$good_id))->find();
        foreach ($order_goods as $k => $v) {
            $good = M('goods')->where(array('id'=>$v['good_id']))->getField('name');
            $goods[] = $good;
        }
        return implode(',', $goods);
    }



    public function order_user($user_id) {
        $order_users = M('user_good_order')->field('user_id')->where(array('user_id'=>$user_id))->find();
        foreach ($order_users as $k => $v) {
            $user = M('user')->where(array('id'=>$v['user_id']))->getField('username');
            $users[] = $user;
        }
        return implode(',', $users);
    } 
	
}